package com.wikidot.designpatterns.composite.alternative2;

public class Client {
	public static void main(String[] args) {
		// Create components
		Component a = new Composite("a");
		Component ab1 = new Composite("ab1");
		Component ab2 = new Composite("ab2");
		Component ab1c1 = new Leaf("ab1c1");
		Component ab1c2 = new Leaf("ab1c2");
		Component ab2c1 = new Leaf("ab2c1");

		// Build structure
		ab1.addComponent(ab1c1);
		ab1.addComponent(ab1c2);
		ab2.addComponent(ab2c1);
		a.addComponent(ab1);
		a.addComponent(ab2);

		// Call business operation
		a.businessOperation();

		System.out.println("\nTry to add descendant to leaf node. Print its structure\n");
		addDescendantToLeaf(ab1c1);
	}

	/**
	 * This method illustrates problem that can occur with this type of
	 * implementation. As Leaf implementation inherits composite structure
	 * management logic there can be easily added descendants to leaf nodes.
	 * After that, leaf becomes internally structured but it might not be aware
	 * of it - as it is in this case. The descendants of leaves might be then
	 * omitted in business processing and that is obviously wrong.
	 * 
	 * @param ab1c1
	 *            Component of type leaf
	 */
	private static void addDescendantToLeaf(Component ab1c1) {
		// ab1c1 is created as instance of Leaf
		ab1c1.addComponent(new Leaf("ab1c1d1"));
		// This will not traverse ab1c1d1 node - Leaf implementation does not
		// count with that.
		ab1c1.businessOperation();
	}
}
